import layui from './Libs/layui/layui.all.js';
import CryptoJS from 'crypto-js';
import MD5 from './Libs/Cry/MD5.js';
import Vue from 'vue'
import axios from 'axios'
import router from '../router'
import electron from 'electron'

let $this;
let __broadcasts = [];
let layer_progress;

export default {
    DEBUG: process.env.NODE_ENV === 'development',
    webName: "YFree_Electron",
    IP: "",
    encryptParamsAble: false,
    encryptParamsKey: "0000000000000000",
    onYHTTPHeader: () => {
    },
    // function
    yInit: function (onYConfig) {
        $this = this;
        onYConfig($this);
        Vue.prototype.yFree = $this;
        electron.remote.app.setName($this.webName);
    },
    yElectron: function () {
        return electron;
    },
    yIPCSend: function (tag) {
        $this.yElectron().ipcRenderer.send(tag);
    },
    yPost: function (jkid, params, onSuccess, onFail = null, showProgress = true, showErrorToast = true) {
        if ($this.yIsEmpty($this.IP)) {
            //yToast("请正确配置YFree：IP");
            if (onFail != null) onFail(-999, "请正确配置YFree：IP");
            return null;
        }
        if (showProgress) $this.yShowProgress();
        return axios({
            method: "post",
            url: $this.IP,
            params: {
                jkid: jkid,
                jkparam: $this.encryptParamsAble ? $this.yAesEncrypt($this.yToJson(params), $this.encryptParamsKey) : $this.yToJson(params)
            },
            timeout: 15000,
            header: $this.onYHTTPHeader(),
            dataType: "text",
            responseType: "text",
        }).then(function (res) {
            if (res.status === 200) {
                let response = $this.encryptParamsAble ? $this.yFromJson($this.yAesEncrypt($this.yToJson(res.data), $this.encryptParamsKey)) : res.data;
                $this.yLog(jkid + ":responseSuccess:" + $this.yToJson(response));
                if (showProgress) $this.yDismissProgress();
                if (response != "") {
                    try {
                        let root = response.root;
                        if (root.code == 1) {
                            onSuccess(root.result);
                        } else {
                            if (showErrorToast) $this.yToast($this.DEBUG ? "网络请求回执message：\n" + root.message : root.message, 2);
                            if (onFail != null) onFail(root.code, root.message);
                        }
                    } catch (e) {
                        let msg = $this.DEBUG ? "网络请求回执message解析异常，响应字符串：\n" + $this.yToJson(response) : "网络请求错误，请重试";
                        if (showErrorToast) $this.yToast(msg, 2);
                        if (onFail != null) onFail("", msg);
                    }
                } else {
                    if (showErrorToast) $this.yToast($this.DEBUG ? "网络请求回执message解析异常，响应字符串：\n（空）" : "网络请求错误，请重试", 2);
                    if (onFail != null) onFail("", "");
                }
            } else {
                $this.yLog(jkid + ":responseFailure:" + "网络请求错误！！！\tErrorNo:" + res.status);
                if (showProgress) $this.yDismissProgress();
                if (showErrorToast) $this.yToast($this.DEBUG ? "网络请求错误！！！\nErrorNo:" + res.status : "网络请求错误，请重试", 2);
                if (onFail) onFail(res.status.toString(), "网络请求错误");
            }
        }).catch(function (error) {
            $this.yLog(jkid + ":responseFailure:" + "网络请求异常！！！\tMsg:" + error.message);
            if (showProgress) $this.yDismissProgress();
            if (showErrorToast) $this.yToast($this.DEBUG ? "网络请求异常！！！\nMsg:" + error.message : "网络请求错误，请重试", 2);
            if (onFail) onFail(error.response.status.toString(), error.message);
        });
    },
    ySetTitle: function (title) {
        document.title = title;
    },
    yCopy: function (content) {
        electron.clipboard.writeText(content);
    },
    ySave: function (key, value) {
        localStorage.setItem(key, value);
    },
    ySaveObj: function (key, obj) {
        localStorage.setItem(key, $this.yToJson(obj));
    },
    yRead: function (key) {
        return localStorage.getItem(key);
    },
    yReadObj: function (key) {
        return $this.yFromJson(localStorage.getItem(key));
    },
    yDelete: function (key) {
        localStorage.removeItem(key);
    },
    yBundle: function () {
        return router.query;
    },
    yIntent: function (page, param = {}, type = 1) {
        param = (param == null ? {} : param);
        switch (type) {
            case 0: //替换
                router.replace({path: page, query: param});
                break;
            case 1: //前进
                router.push({path: page, query: param});
                break;
        }
    },
    yFinishToHome: function () {
        router.go(-99);
    },
    yFinish: function (delta = -1) {
        router.go(delta);
    },
    yRefresh: function (context) {
        location.reload();
    },
    yRunOnDelay: function (delay, action) {
        return setTimeout(action, delay);
    },
    yRunOnLoop: function (loopTime, action, firstDelay = false) {
        if (!firstDelay) action();
        return setInterval(action, loopTime);
    },
    yStopRun: function (task) {
        clearTimeout(task);
        clearInterval(task);
    },
    yIsEmpty: function (obj) {
        return obj == null || obj.toString() === "";
    },
    yIsNotEmpty: function (obj) {
        return obj != null && obj.toString() !== "";
    },
    yLog: function (content) {
        if ($this.DEBUG) console.log(content);
    },
    yToast: function (msg, icon = 1) {
        layui.layer.msg(msg, {
            time: 2000,
            icon: icon,
        });
    },
    yShowProgress: function (style = 0) {
        layer_progress = layui.layer.load(style, {
            shade: [0.3, '#000'],
        });
    },
    yDismissProgress: function () {
        if (layer_progress != null) {
            layui.layer.close(layer_progress);
            layer_progress = null;
        }
    },
    yShowBuilder: function (msg, btn, callback, showClose = true, icon = 1) {
        let builder = layui.layer.open({
            title: `${$this.webName}提示`,
            content: msg,
            btn: btn,
            shadeClose: false,
            icon: icon,
            closeBtn: showClose ? 1 : 0,
            yes: function (index, layero) {
                layui.layer.close(builder);
                callback(1);
            },
            btn2: function (index, layero) {
                layui.layer.close(builder);
                callback(2);
            },
            btn3: function (index, layero) {
                layui.layer.close(builder);
                callback(3);
            },
            btn4: function (index, layero) {
                layui.layer.close(builder);
                callback(4);
            },
            cancel: function () {
                layui.layer.close(builder);
                callback(0);
            },
        });
    },
    yNotification: function (content, onclick) {
        Notification.requestPermission().then(function (permission) {
            if (permission === 'granted')
                new Notification($this.webName, {
                    body: content,
                    requireInteraction: false,
                }).onclick = onclick;
            else $this.yToast(content);
        });
    },
    yToJson: function (obj) {
        return JSON.stringify(obj);
    },
    yFromJson: function (json) {
        return $this.yIsEmpty(json) ? null : JSON.parse(json);
    },
    yRegisterReceiver: function (name, selector) {
        if (name && selector)
            __broadcasts.push({
                name: name,
                selector: selector
            });
    },
    yDeleteReceiver: function (name) {
        for (var i = 0; i < __broadcasts.length; i++)
            if (__broadcasts[i].name === name) {
                __broadcasts.splice(i, 1);
                return;
            }
    },
    ySendBroadcast: function (name, info = {}) {
        if (__broadcasts.length === 0) return;
        for (var i = 0; i < __broadcasts.length; i++)
            if (__broadcasts[i].name === name) __broadcasts[i].selector(info);
    },
    yMD5: function (content) {
        return MD5.hex_md5(content);
    },
    yAesEncrypt: function (content, password) {
        return String(CryptoJS.AES.encrypt(content, CryptoJS.SHA256(password), {
            iv: CryptoJS.enc.Hex.parse("0000000000000000"),
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        }));
    },
    yAesDecrypt: function (content, password) {
        return CryptoJS.AES.decrypt(content.toString(), CryptoJS.SHA256(password), {
            iv: CryptoJS.enc.Hex.parse("0000000000000000"),
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        }).toString(CryptoJS.enc.Utf8);
    },
    base64_encode: function (str) { // 编码，配合encodeURIComponent使用
        var c1, c2, c3;
        var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        var i = 0,
            len = str.length,
            strin = '';
        while (i < len) {
            c1 = str.charCodeAt(i++) & 0xff;
            if (i == len) {
                strin += base64EncodeChars.charAt(c1 >> 2);
                strin += base64EncodeChars.charAt((c1 & 0x3) << 4);
                strin += "==";
                break;
            }
            c2 = str.charCodeAt(i++);
            if (i == len) {
                strin += base64EncodeChars.charAt(c1 >> 2);
                strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                strin += base64EncodeChars.charAt((c2 & 0xF) << 2);
                strin += "=";
                break;
            }
            c3 = str.charCodeAt(i++);
            strin += base64EncodeChars.charAt(c1 >> 2);
            strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            strin += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
            strin += base64EncodeChars.charAt(c3 & 0x3F)
        }
        return strin
    },
    base64_decode: function (input) { // 解码，配合decodeURIComponent使用
        let base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        let output = "";
        let chr1, chr2, chr3;
        let enc1, enc2, enc3, enc4;
        let i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            let enc1 = base64EncodeChars.indexOf(input.charAt(i++));
            let enc2 = base64EncodeChars.indexOf(input.charAt(i++));
            let enc3 = base64EncodeChars.indexOf(input.charAt(i++));
            let enc4 = base64EncodeChars.indexOf(input.charAt(i++));
            let chr1 = (enc1 << 2) | (enc2 >> 4);
            let chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            let chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) output = output + String.fromCharCode(chr2);
            if (enc4 != 64) output = output + String.fromCharCode(chr3);
        }
        return $this.utf8_decode(output);
    },
    utf8_decode: function (utftext) { // utf-8解码
        let string = '';
        let i = 0;
        let c = 0;
        let c1 = 0;
        let c2 = 0;
        while (i < utftext.length) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c1 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
                i += 2;
            } else {
                c1 = utftext.charCodeAt(i + 1);
                c2 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
                i += 3;
            }
        }
        return string;
    },
}

/* String */
String.prototype.contains = function (text) {
    return this.indexOf(text) >= 0;
};

String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
}

/* Array */
Array.prototype.indexOf = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};

Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

Array.prototype.contains = function (val) {
    return this.indexOf(val) > -1;
};

/* Date Format */
Date.prototype.format = function (fmt) { //author: meizz
    let o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
